<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <script>
      var NumArray = function (nums) {
        // this.nums = nums;

        // 采用前缀和
        this.preSum = new Array(nums.length + 1);
        this.preSum[0] = 0;
        for (let i = 1; i < this.preSum.length; i++) {
          this.preSum[i] = this.preSum[i - 1] + nums[i - 1];
        }
      };
      NumArray.prototype.sumRange = function (left, right) {
        // let sum = 0;
        // for (let i = left; i <= right; i++) {
        //   sum += this.nums[i];
        // }
        // return sum;

        // 采用前缀和
        return this.preSum[right + 1] - this.preSum[left];
      };
      const numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
      console.log(numArray.sumRange(0, 2));
      console.log(numArray.sumRange(2, 4));
    </script>
  </body>
</html>
